<script setup> 
import { ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { queryPageApi, addGameDataApi, queryInfoApi, updateGameDataApi, deleteGameDataApi } from '@/api/gameData'
import { queryAllApi as queryAllCategoriesApi } from '@/api/gameCategory'

//游戏数据列表
const gameList = ref([])
//分类列表
const categoryList = ref([])

const searchGame = ref({
  name: '',
  categoryId: ''
})

// 移除重复的onMounted函数

// 加载分类数据
const loadCategories = async () => {
  const result = await queryAllCategoriesApi()
  if (result.code === 1) {
    categoryList.value = result.data
  }
}

//查询游戏数据
const handleSearch = async () => {
  console.log('Search:', searchGame.value)
  const result = await queryPageApi(
    searchGame.value.name, 
    searchGame.value.categoryId, 
    currentPage.value, 
    pageSize.value
  );
  if(result.code === 1){
    gameList.value = result.data.records
    total.value = result.data.total
  }
}

const handleReset = () => {
  // 清空表单
  searchGame.value = {
    name: '',
    categoryId: ''
  }
  handleSearch()
}

// 分页配置
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}

// 操作处理
const handleEdit = async (id) => {
  console.log('Edit:', id)
  const result = await queryInfoApi(id);
  if(result.code === 1){
    dialogVisible.value = true
    dialogTitle.value = '修改游戏数据'
    game.value = result.data
  }
  gameFormRef.value.resetFields()
}

// 删除单个游戏数据
const handleDelete = async (id) => {
  //弹出一个确认框, 如果确认, 就删除;
  ElMessageBox.confirm('确定删除该游戏数据吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 删除游戏数据
    const result = await deleteGameDataApi(id);
    if(result.code === 1){
      ElMessage.success('删除游戏数据成功') 
      handleSearch()
    }else{
      ElMessage.error(result.msg || '删除失败')
    }
  })
}

//新增游戏数据
const addGame = () => {
  dialogVisible.value = true
  dialogTitle.value = '新增游戏数据'
  // 确保初始化时有正确的coverImage字段
  game.value = {
    name: '',
    price: 0,
    releaseDate: '',
    historyLowPrice: 0,
    playerCount: 0,
    description: '',
    coverImage: '',
    categoryId: ''
  }
  gameFormRef.value.resetFields()
}

//新增/修改表单
const gameFormRef = ref(null)
const game = ref({
  name: '',
  price: 0,
  releaseDate: '',
  historyLowPrice: 0,
  playerCount: 0,
  description: '',
  coverImage: '',
  categoryId: ''
})

//表单校验规则
const rules = ref({
  name: [
    { required: true, message: '请输入游戏名称', trigger: 'blur' },
    { min: 1, max: 100, message: '游戏名称长度应在1到100个字符之间', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入游戏价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格不能为负数', trigger: 'blur' }
  ],
  releaseDate: [
    { required: true, message: '请选择发布日期', trigger: 'change' }
  ],
  historyLowPrice: [
    { required: true, message: '请输入历史最低价', trigger: 'blur' },
    { type: 'number', min: 0, message: '历史最低价不能为负数', trigger: 'blur' }
  ],
  playerCount: [
    { required: true, message: '请输入玩家数量', trigger: 'blur' },
    { type: 'number', min: 0, integer: true, message: '玩家数量必须是非负整数', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择游戏分类', trigger: 'change' }
  ]
});

// 控制弹窗状态
const dialogVisible = ref(false)
const dialogTitle = ref('新增游戏数据')

//声明token
const token = ref('')

onMounted(async () => {
  // 加载分类数据
  await loadCategories()
  // 查询游戏列表
  handleSearch()
  
  //加载localStorage存储的用户登录信息
  const loginUser = localStorage.getItem('loginUser');
  if(loginUser){
    token.value = JSON.parse(loginUser).token
  }
})

// 图片上传成功后触发
const handleCoverSuccess = (response,uploadFile) => {
  ElMessage.success('图片上传成功')
  // 确保能正确处理不同格式的响应数据
  const imageUrl = response.data?.url || response.data || ''
  game.value.coverImage = imageUrl
  console.log('上传的图片URL:', imageUrl)
}
// 文件上传之前触发
const beforeCoverUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('只支持上传图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('只能上传10M以内图片')
    return false
  }
  return true
}

//保存游戏数据信息
const save = async () => {
  gameFormRef.value.validate(async valid => {
    if(valid){ // 校验通过
      // 创建提交数据的副本，确保coverImage正确包含
      const submitData = { ...game.value }
      console.log('提交到后端的数据:', submitData)
      
      let result ;
      if(submitData.id){ //存在ID, 修改
        result = await updateGameDataApi(submitData);
      }else { //不存在ID, 新增
        result = await addGameDataApi(submitData);
      }
      if(result.code === 1){
        ElMessage.success('保存游戏数据成功')
        dialogVisible.value = false
        handleSearch()
      }else { 
        ElMessage.error(result.msg || '保存失败')
      }
    }
  })
}

// 存储选中的 ID
const selectedIds = ref([]);

// 处理复选框选择变化的函数
function handleSelectionChange(selection) {
  const ids = selection.map(item => item.id);
  selectedIds.value = ids;
}

//批量删除游戏数据
const deleteByIds = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请先选择要删除的游戏数据')
    return
  }
  
  //弹出一个确认框, 如果确认, 就删除;
  ElMessageBox.confirm('确定删除选中的游戏数据吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 删除游戏数据
    const result = await deleteGameDataApi(selectedIds.value.join(','));
    if(result.code === 1){
      ElMessage.success('删除游戏数据成功')
      handleSearch()
      selectedIds.value = []
    }else{ 
      ElMessage.error(result.msg || '删除失败')
    }
  })
}

// 获取分类名称
const getCategoryName = (categoryId) => {
  const category = categoryList.value.find(cat => cat.id === categoryId)
  return category ? category.name : '-'
}
</script>
<template> 
<h1>游戏数据管理</h1> <br>
  <el-form :inline="true" :model="searchGame">
    <el-form-item label="游戏名称">
      <el-input v-model="searchGame.name" placeholder="请输入游戏名称"></el-input>
    </el-form-item>
    
    <el-form-item label="游戏分类">
      <el-select v-model="searchGame.categoryId" placeholder="请选择分类">
        <el-option label="全部" value=""></el-option>
        <el-option 
          v-for="category in categoryList" 
          :key="category.id" 
          :label="category.name" 
          :value="category.id"
        ></el-option>
      </el-select>
    </el-form-item>
    
    <el-form-item>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">清空</el-button>
    </el-form-item>
  </el-form>


  <el-button type="primary" @click="addGame"> + 新增游戏</el-button>
  <el-button type="danger" @click="deleteByIds"> - 批量删除</el-button>
  <br><br>

  <!-- 表格 -->
  <el-table :data="gameList" border style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="50" align="center"></el-table-column>
    <el-table-column prop="name" label="游戏名称" width="180" align="center"></el-table-column>
    <el-table-column label="游戏分类" width="120" align="center">
      <template #default="scope">
        {{ getCategoryName(scope.row.categoryId) }}
      </template>
    </el-table-column>
    <el-table-column prop="price" label="价格" width="100" align="center">
      <template #default="scope">
        ¥{{ scope.row.price.toFixed(2) }}
      </template>
    </el-table-column>
    <el-table-column prop="historyLowPrice" label="历史最低价" width="120" align="center">
      <template #default="scope">
        ¥{{ scope.row.historyLowPrice.toFixed(2) }}
      </template>
    </el-table-column>
    <el-table-column prop="releaseDate" label="发布日期" width="120" align="center"></el-table-column>
    <el-table-column prop="playerCount" label="玩家数量" width="100" align="center"></el-table-column>
    <el-table-column prop="description" label="描述" min-width="150" align="center">
      <template #default="scope">
        {{ scope.row.description || '-' }}
      </template>
    </el-table-column>
    <el-table-column label="封面图片" width="100" align="center">
      <template #default="scope">
        <img v-if="scope.row.coverImage" :src="scope.row.coverImage" alt="Cover" class="cover-image" />
        <span v-else>-</span>
      </template>
    </el-table-column>
    <el-table-column label="操作" fixed="right" align="center" width="150">
      <template #default="scope">
        <el-button size="small" type="primary" @click="handleEdit(scope.row.id)">编辑</el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <br>

  <!-- 分页 -->
  <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="currentPage"
    :page-sizes="[10, 20, 30, 40]"
    :page-size="pageSize"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
  >
  </el-pagination>

  <!-- 新增/修改游戏数据的对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form ref="gameFormRef" :model="game" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="游戏名称" prop="name">
              <el-input v-model="game.name" placeholder="请输入游戏名称"></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <el-form-item label="游戏分类" prop="categoryId">
              <el-select v-model="game.categoryId" placeholder="请选择游戏分类" style="width: 100%">
                <el-option 
                  v-for="category in categoryList" 
                  :key="category.id" 
                  :label="category.name" 
                  :value="category.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input v-model.number="game.price" placeholder="请输入价格" type="number" step="0.01"></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="历史最低价" prop="historyLowPrice">
              <el-input v-model.number="game.historyLowPrice" placeholder="请输入历史最低价" type="number" step="0.01"></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="发布日期" prop="releaseDate">
              <el-date-picker
                v-model="game.releaseDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择发布日期"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="玩家数量" prop="playerCount">
              <el-input v-model.number="game.playerCount" placeholder="请输入玩家数量" type="number" step="1"></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <el-form-item label="游戏描述">
              <el-input 
                v-model="game.description" 
                placeholder="请输入游戏描述（可选）"
                type="textarea"
                :rows="3"
              ></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <el-form-item label="封面图片">
              <el-upload
                class="avatar-uploader"
                action="/api/upload"
                :headers="{'token': token}"
                :show-file-list="false"
                :on-success="handleCoverSuccess"
                :before-upload="beforeCoverUpload"
                >
                <img v-if="game.coverImage" :src="game.coverImage" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </span>
      </template>
  </el-dialog>

</template>
<style scoped> 
.cover-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>